<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      
      
      <el-form-item label="配置名称" prop="timeId">
        <el-select
          v-model="queryParams.timeId"
          placeholder="请选择配置"
          clearable
          filterable
        >
          <el-option
            v-for="item in seckillMangerList"
            :key="item.id"
            :label="`${item.name} - ${formatTimeRange(item.startTime, item.endTime)}`"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品搜索" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="openForm(undefined)"
          v-hasPermi="['eb:store-seckill:create']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
    >
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column
        label="配置名称"
        align="center"
        width="100"
      >
        <template v-slot="scope">
          {{ scope.row.mangerName }}
        </template>
      </el-table-column>
      <el-table-column label="秒杀时段" align="center" width="180">
        <template v-slot="scope">
          <div>
            <div>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }} - {{ parseTime(scope.row.stopTime, '{y}-{m}-{d}') }}</div>
            <div>{{ formatTimeRange(scope.row.mangerStartTime, scope.row.mangerEndTime) }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="秒杀状态"
        align="center"
        prop="status"
      >
        <template v-slot="scope">
          <el-tag :type="getSeckillStatusType(scope.row)">
            {{ getSeckillStatusText(scope.row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="商品图片" align="center" prop="image">
        <template v-slot="scope">
          <el-image 
            style="width: 50px; height: 50px"
            :src="scope.row.image"
            :preview-src-list="[scope.row.image]"
            fit="cover">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column width="260" label="商品标题" align="center" prop="title" show-overflow-tooltip />
      <el-table-column width="260" label="活动简介" align="center" prop="info" show-overflow-tooltip />
      <el-table-column label="原价" align="center" prop="otPrice" />
      <el-table-column label="秒杀价" align="center" prop="price" />
      
      <el-table-column
        label="限量"
        align="center"
        prop="quotaShow"
      />
      <el-table-column label="限量剩余" align="center" prop="quota" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
        prop="status"
        fixed="right"
        width="100"
      >
        <template v-slot="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="150"
      >
        <template v-slot="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="openForm(scope.row.id, scope.row)"
            v-hasPermi="['eb:store-seckill:update']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['eb:store-seckill:delete']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import * as StoreSeckillApi from "@/api/marketing/storeseckill";
import * as StoreSeckillMangerApi from "@/api/marketing/storeseckillmanger";
export default {
  name: "StoreSeckill",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品秒杀产品列表
      list: [],
      // 秒杀管理列表
      seckillMangerList: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        title: null,
        status: null,
        timeId: null,
      },
      statusOptions: [
        { value: 1, label: '开启' },
        { value: 0, label: '关闭' }
      ],
    };
  },
  created() {
    this.getList();
    this.getSeckillMangerList();
  },
  activated() {
    this.getList();
  },
  methods: {
    /** 获取秒杀管理列表 */
    async getSeckillMangerList() {
      try {
        const res = await StoreSeckillMangerApi.getStoreSeckillMangerPage({
          pageNo: 1,
          pageSize: 10,
          status: 1 // 只获取开启状态的配置
        });
        if (res.code === 0) {
          this.seckillMangerList = res.data.list;
        } else {
          this.$message.error(res.msg || '获取秒杀管理列表失败');
        }
      } catch (error) {
        console.error('获取秒杀管理列表失败:', error);
        this.$message.error('获取秒杀管理列表失败');
      }
    },
    // 格式化时间段
    formatTimeRange(start, end) {
      if (start === null || end === null) return '-';
      return `${this.formatHour(start)} - ${this.formatHour(end)}`;
    },
    // 格式化单小时
    formatHour(hour) {
      const hourStr = (typeof hour === 'number' ? hour : 0).toString();
      return hourStr.padStart(2, '0') + ':00';
    },
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await StoreSeckillApi.getStoreSeckillPage(this.queryParams);
        this.list = res.data.list;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id, row) {
      // 如果传入 row，优先用 row.status 判断
      if (row && row.status === 1) {
        this.$message.warning('请关闭秒杀状态再进行操作');
        return;
      }
      if (id) {
        // 编辑模式
        this.$router.push({
          path: '/marketing/storeseckill/creatSeckill',
          query: { id: id }
        });
      } else {
        // 新增模式
        this.$router.push({
          path: '/marketing/storeseckill/creatSeckill'
        });
      }
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm(
        '是否确认删除商品秒杀产品编号为"' + id + '"的数据项?'
      );
      try {
        await StoreSeckillApi.deleteStoreSeckill(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {}
    },
    /** 修改状态 */
    async handleStatusChange(row) {
      try {
        // 显示加载状态（可选）
        row.loading = true;

        // 调用 API 更新状态
        const res = await StoreSeckillApi.updateStatus({
          id: row.id,
          status: row.status
        });

        // 更新成功提示
        this.$message.success(res.message || '状态更新成功');
      } catch (error) {
        // 失败时回滚状态
        row.status = row.status === 1 ? 0 : 1;
        this.$message.error(error.message || '状态更新失败');
      } finally {
        // 隐藏加载状态
        row.loading = false;
      }
    },
    // 获取秒杀状态文本
    getSeckillStatusText(row) {
      if (row.status === 0) {
        return '已关闭';
      }
      
      const now = new Date();
      const startDate = new Date(row.startTime);
      const endDate = new Date(row.stopTime);
      
      // 设置开始和结束时间的小时
      startDate.setHours(row.mangerStartTime, 0, 0, 0);
      endDate.setHours(row.mangerEndTime, 0, 0, 0);
      
      // 获取今天的开始时间（00:00:00）
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      
      // 获取今天的秒杀开始和结束时间
      const todayStart = new Date(today);
      todayStart.setHours(row.mangerStartTime, 0, 0, 0);
      
      const todayEnd = new Date(today);
      todayEnd.setHours(row.mangerEndTime, 0, 0, 0);
      
      // 判断是否在活动日期范围内
      const isInDateRange = now >= startDate && now <= endDate;
      
      if (!isInDateRange) {
        if (now < startDate) {
          return '未开始';
        } else {
          return '已结束';
        }
      }
      
      // 在日期范围内，判断时段
      if (now < todayStart) {
        return '未开始';
      } else if (now > todayEnd) {
        // 检查是否是最后一天
        const tomorrow = new Date(today);
        tomorrow.setDate(tomorrow.getDate() + 1);
        const isLastDay = tomorrow > endDate;
        
        if (isLastDay) {
          return '已结束';
        } else {
          return '未开始';
        }
      } else {
        return '进行中';
      }
    },
    
    // 获取秒杀状态标签类型
    getSeckillStatusType(row) {
      const status = this.getSeckillStatusText(row);
      switch (status) {
        case '进行中':
          return 'success';
        case '未开始':
          return 'info';
        case '已结束':
          return 'warning';
        case '已关闭':
          return 'danger';
        default:
          return 'info';
      }
    },
  },
};
</script>
